<template>
  <div class="chat-container">
    <!-- 头部 -->
    <header class="chat-header">
      <h1>🤖 AI编程小助手</h1>
      <p>会话ID: {{ memoryId }}</p>
    </header>

    <!-- 聊天记录区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        :class="['message', message.type]"
      >
        <div class="message-avatar">
          <div v-if="message.type === 'ai'" class="ai-avatar">🤖</div>
          <div v-else class="user-avatar">👤</div>
        </div>
        <div class="message-content">
          <div class="message-text" v-html="message.content"></div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="isLoading" class="message ai">
        <div class="message-avatar">
          <div class="ai-avatar">🤖</div>
        </div>
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input-container">
      <div class="input-wrapper">
        <textarea
          v-model="inputMessage"
          @keydown.enter.prevent="sendMessage"
          placeholder="请输入您的编程问题..."
          class="chat-input"
          :disabled="isLoading"
          rows="1"
          ref="inputRef"
        ></textarea>
        <button 
          @click="sendMessage" 
          class="send-button"
          :disabled="!inputMessage.trim() || isLoading"
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="22" y1="2" x2="11" y2="13"></line>
            <polygon points="22,2 15,22 11,13 2,9"></polygon>
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick, watch } from 'vue'
import axios from 'axios'

export default {
  name: 'App',
  setup() {
    const messages = ref([])
    const inputMessage = ref('')
    const isLoading = ref(false)
    const memoryId = ref('')
    const messagesContainer = ref(null)
    const inputRef = ref(null)
    let eventSource = null

    // 生成随机会话ID
    const generateMemoryId = () => {
      return Math.floor(Math.random() * 1000000).toString()
    }

    // 格式化时间
    const formatTime = () => {
      return new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 自动调整输入框高度
    const adjustTextareaHeight = () => {
      const textarea = inputRef.value
      if (textarea) {
        textarea.style.height = 'auto'
        textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
      }
    }

    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
      })
    }

    // 发送消息
    const sendMessage = async () => {
      const message = inputMessage.value.trim()
      if (!message || isLoading.value) return

      // 添加用户消息
      messages.value.push({
        type: 'user',
        content: message,
        time: formatTime()
      })

      const currentMessage = message
      inputMessage.value = ''
      isLoading.value = true
      adjustTextareaHeight()
      scrollToBottom()

      try {
        // 关闭之前的连接
        if (eventSource) {
          eventSource.close()
        }

        // 创建SSE连接
        const url = `http://localhost:8081/api/ai/chat?memoryId=${memoryId.value}&message=${encodeURIComponent(currentMessage)}`
        eventSource = new EventSource(url)

        let aiResponse = ''

        eventSource.onmessage = (event) => {
          if (event.data) {
            aiResponse += event.data
            // 更新或创建AI消息
            const aiMessageIndex = messages.value.findIndex(msg => msg.type === 'ai' && msg.isStreaming)
            
            if (aiMessageIndex === -1) {
              // 创建新的AI消息
              messages.value.push({
                type: 'ai',
                content: aiResponse,
                time: formatTime(),
                isStreaming: true
              })
            } else {
              // 更新现有AI消息
              messages.value[aiMessageIndex].content = aiResponse
            }
            
            scrollToBottom()
          }
        }

        eventSource.onerror = (error) => {
          console.error('SSE连接错误:', error)
          isLoading.value = false
          eventSource.close()
          
          // 如果没有收到任何响应，显示错误消息
          if (!aiResponse) {
            messages.value.push({
              type: 'ai',
              content: '抱歉，连接出现错误，请稍后重试。',
              time: formatTime()
            })
          } else {
            // 完成流式响应
            const aiMessageIndex = messages.value.findIndex(msg => msg.type === 'ai' && msg.isStreaming)
            if (aiMessageIndex !== -1) {
              messages.value[aiMessageIndex].isStreaming = false
            }
          }
        }

        eventSource.onclose = () => {
          isLoading.value = false
          // 完成流式响应
          const aiMessageIndex = messages.value.findIndex(msg => msg.type === 'ai' && msg.isStreaming)
          if (aiMessageIndex !== -1) {
            messages.value[aiMessageIndex].isStreaming = false
          }
        }

      } catch (error) {
        console.error('发送消息失败:', error)
        isLoading.value = false
        messages.value.push({
          type: 'ai',
          content: '抱歉，发送消息失败，请检查网络连接。',
          time: formatTime()
        })
      }
    }

    // 监听输入框变化
    watch(inputMessage, adjustTextareaHeight)

    // 监听消息变化，自动滚动
    watch(messages, scrollToBottom, { deep: true })

    onMounted(() => {
      // 生成会话ID
      memoryId.value = generateMemoryId()
      
      // 添加欢迎消息
      messages.value.push({
        type: 'ai',
        content: '你好！我是AI编程小助手，可以帮助你解答编程学习和求职面试相关的问题。请随时向我提问！',
        time: formatTime()
      })
    })

    return {
      messages,
      inputMessage,
      isLoading,
      memoryId,
      messagesContainer,
      inputRef,
      sendMessage
    }
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 1200px;
  margin: 0 auto;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  margin: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.chat-header {
  padding: 20px 30px;
  border-bottom: 1px solid #e1e5e9;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 20px 20px 0 0;
}

.chat-header h1 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 5px;
}

.chat-header p {
  font-size: 14px;
  opacity: 0.8;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message.ai {
  align-self: flex-start;
}

.message-avatar {
  flex-shrink: 0;
}

.ai-avatar, .user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.ai-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.user-avatar {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.message-content {
  flex: 1;
}

.message-text {
  background: #f8f9fa;
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.message.user .message-text {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.message.ai .message-time {
  text-align: left;
}

.chat-input-container {
  padding: 20px 30px;
  border-top: 1px solid #e1e5e9;
  background: #f8f9fa;
  border-radius: 0 0 20px 20px;
}

.input-wrapper {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.chat-input {
  flex: 1;
  border: 2px solid #e1e5e9;
  border-radius: 25px;
  padding: 12px 20px;
  font-size: 14px;
  resize: none;
  outline: none;
  transition: border-color 0.3s ease;
  font-family: inherit;
  max-height: 120px;
  min-height: 44px;
}

.chat-input:focus {
  border-color: #667eea;
}

.chat-input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.send-button {
  width: 44px;
  height: 44px;
  border: none;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s ease;
  flex-shrink: 0;
}

.send-button:hover:not(:disabled) {
  transform: scale(1.05);
}

.send-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 打字指示器 */
.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 12px 16px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #999;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    margin: 10px;
    border-radius: 15px;
  }
  
  .chat-header {
    padding: 15px 20px;
  }
  
  .chat-messages {
    padding: 15px;
  }
  
  .chat-input-container {
    padding: 15px 20px;
  }
  
  .message {
    max-width: 90%;
  }
}
</style> 